﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Odyssey.Linq;
using Odyssey.Web.Models;

namespace Odyssey.Web.Controllers
{
    public class ArticleController : FrontBaseController
    {
        public ActionResult Detail(int? id)
        {

            var entity = id > 0
                 ? GetTable<tb_article>().FirstOrDefault(c => c.Id == id)
                 : new tb_article();
            ViewData.Model = entity;
            BindMasterViewData(entity.TopClassId);

            var subClass = entity.ClassId > 0
                 ? GetTable<tb_subclass>().FirstOrDefault(c => c.Id == entity.ClassId)
                 : new tb_subclass();
            ViewBag.SubClass = subClass;

            return View();
        }

        public ActionResult View(string topClass, string subClass, string urlCode)
        {
            var articles = db.tb_articles.Where(c => c.UrlCode == urlCode).ToList();
            if (articles.Count == 1)
            {
                // 匹配到唯一一条记录
                ViewData.Model = articles[0];
                ViewBag.SubClass = CacheHelper<tb_subclass>.GetById(articles[0].ClassId);
                BindMasterViewData(articles[0].TopClassId);
            }
            else
            {
                var sc = CacheHelper<tb_subclass>.GetAll().FirstOrDefault(c => c.UrlCode == subClass);
                if (sc != null)
                {
                    ViewData.Model = articles.FirstOrDefault(c => c.ClassId == sc.Id);
                    ViewBag.SubClass = sc;
                    BindMasterViewData(sc.TopClassId);
                }
            }

            return View("Detail");
        }
    }
}
